// pages/publish/index/index.js
import common from "../../../common/compents.js";
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import * as echarts from '../../ec-canvas/echarts.js';
import geoJson from './mapData.js';
let App = getApp();
let myMap = null,
  oneComponent = null,mapOptions;
let chartComponent = null,
  myChart, myOptions;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indexPower: true,
    chartPower: true,
    goodsPower: true,
    catePower: true,
    regionPower: true,
    animationData: {},
    choose: 1,
    baseInfo: {
      on_sale_num: 0, // 在售品种数
      reader_num: 0, // 读者基数
      sale_total: 0, // 累计销售指数
      sale_total_info: { // 销售指数
        now: 0
      },
      sale_rank_info: { // 行业排名
        now: 0
      },
      sale_ratio_info: { // 行业占有率
        now: 0
      },
      onsale_goods_info: { // 动销品种数
        now: 0
      }
    },
    period: common.weekDate().weekth,
    date_type: 2,
    start_date: common.weekDate().start.replace(/-/g, ''),
    time: '第' + common.weekDate().weekth.slice(-2) + '周 ' + common.weekDate().start + '~' + common.weekDate().end,
    show: false,
    title: "文学",
    showChart: false,
    onInitChart: null,
    type: "sale_total",
    chartList: [],
    goodsList: [],
    cateList: [],
    regionList: [],
    setRegionList: [],
    cateGoodsList: [],
    // 控制地图遮挡弹层显隐
    visible: true,
    ecMap: {
      lazyLoad: true //设置图表懒加载
    },
    ecChart: {
      lazyLoad: true //设置图表懒加载
    },
    chartSrc: "",
    kernelList: null,
    active: 0,
    isHand: false,
    shareShow: false,
    coreHeight: 0,
    goodsHeight: 0,
    cateHeight: 0,
    regionHeight: 0,
  },
  // 本社基础信息
  getBaseInfo() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/myview/index',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        period: that.data.period,
        date_type: that.data.date_type,
        start_date: that.data.start_date,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            indexPower: true,
            baseInfo: resapi.data.data
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            indexPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取图表数据
  getChartData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/myview/kernelchart',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        period: that.data.period,
        date_type: that.data.date_type,
        start_date: that.data.start_date,
        type: that.data.type,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            showChart: false
          })
          let _arr = [];
          for (let i = 0; i < resapi.data.data.current_data.length; i++) {
            if (resapi.data.data.last_data.length > i) {
              let _obj = resapi.data.data.last_data[i];
              _obj.city = "上年同期";
              _arr.unshift(_obj);
            }
            if (resapi.data.data.current_data.length > i) {
              let _obj = resapi.data.data.current_data[i];
              _obj.city = "当期";
              _arr.unshift(_obj);
            }
          }
          // console.log(_arr)
          that.setData({
            chartPower: true,
            chartList: _arr,
            onInitChart: (F2, config) => that.initChart(F2, config, _arr),
            showChart: true,
            kernelList: resapi.data.data,
          })
          wx.nextTick(() => {
            that.kernelChart();
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            chartPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取品种数据
  getGoodsData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/myview/goodsrank',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        period: that.data.period,
        date_type: that.data.date_type,
        start_date: that.data.start_date,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            goodsPower: true,
            goodsList: resapi.data.data
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            goodsPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取类目数据
  getCateData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/myview/caterank',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        period: that.data.period,
        date_type: that.data.date_type,
        start_date: that.data.start_date,
        category_level: 'one',
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            catePower: true,
            cateList: resapi.data.data.category_ranks
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            catePower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  // 获取地域数据
  getRegionData() {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/myview/region',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        period: that.data.period,
        date_type: that.data.date_type,
        start_date: that.data.start_date,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          let _arr = [];
          let _set = resapi.data.data.rank_list.slice(0, 7);
          // console.log(_set)
          for (let i = 0; i < _set.length; i++) {
            let _obj = {};
            _obj.name = resapi.data.data.rank_list[i].name;
            _obj.itemStyle = {};
            if (i == 0) {
              _obj.itemStyle.areaColor = "#4777D8";
            } else if (i == 1) {
              _obj.itemStyle.areaColor = "#6E94E1";
            } else if (i == 2) {
              _obj.itemStyle.areaColor = "#82A3E5";
            } else if (i == 3) {
              _obj.itemStyle.areaColor = "#96B2E8";
            } else if (i == 4) {
              _obj.itemStyle.areaColor = "#A0B9EA";
            } else if (i == 5) {
              _obj.itemStyle.areaColor = "#BDCEF1";
            } else {
              _obj.itemStyle.areaColor = "#D1DDF5";
            }
            _arr.push(_obj)
          }
          // console.log(_arr)
          that.setData({
            regionPower: true,
            regionList: resapi.data.data.rank_list,
            setRegionList: _arr,
            visible: true,
          })
          if (that.data.regionList.length > 0) {
            wx.nextTick(() => {
              oneComponent = that.selectComponent('#chartmap');
              that.initChartMap();
            })
          }
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            regionPower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
        let query = wx.createSelectorQuery();
        wx.nextTick(() => {
          query.select('.core-data').boundingClientRect(function (rect) {
            that.setData({
              coreHeight: rect.height
            })
          }).exec();
          query.select('.goods-card').boundingClientRect(function (rect1) {
            that.setData({
              goodsHeight: rect1.height
            })
          }).exec();
          query.select('.cate-card').boundingClientRect(function (rect2) {
            that.setData({
              cateHeight: rect2.height
            })
          }).exec();
          query.select('.region-card').boundingClientRect(function (rect3) {
            that.setData({
              regionHeight: rect3.height
            })
          }).exec();
        })
      }
    })
  },
  // 获取某个类目下商品排行
  getCateGoodsData(id) {
    let _token = wx.getStorageSync('token'),
      _obj = JSON.parse(wx.getStorageSync('currentOrganize')),
      that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/myview/categoodsrank',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "token": _token
      },
      data: {
        supplier_id: _obj.supplier_id,
        organization_id: _obj.organization_id,
        period: that.data.period,
        date_type: that.data.date_type,
        start_date: that.data.start_date,
        category_level: 'one',
        category_id: id,
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          that.setData({
            show: true,
            cateGoodsList: resapi.data.data,
            visible: false
          })
        } else if (resapi.data.code == 1008) {
          common.reLogin();
        } else if (resapi.data.code == 1009) {
          that.setData({
            pagePower: false
          });
        } else {
          Toast(resapi.data.message)
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      },
      complete(resapi) {
        wx.hideLoading();
      }
    })
  },
  initChart(F2, config, data) {
    let _dom = config,
      that = this;
    _dom.padding = [0, 10];
    const chart = new F2.Chart(_dom);
    chart.source(data, {
      value: {
        min: 0
      }
    });
    chart.axis(false);
    chart.legend(false);
    chart.tooltip({
      showItemMarker: false,
      showTitle: true,
      offsetY: 45,
      background: {
        radius: 4,
        padding: [5, 10],
      },
      onChange: function onShow(ev) {
        // console.log(ev)
        const items = ev.items;
        if (that.data.date_type == 2) {
          items[0].title = items[0].origin.date + '（' + items[0].origin.week_range + '）';
        } else {
          items[0].title = items[0].origin.date;
        }
        items[0].name = items[0].origin.city;
        if (that.data.type == 'sale_ratio') {
          items[0].value = items[0].origin.value + '%';
          items[1].value = items[1].origin.value + '%';
        } else {
          items[0].value = items[0].origin.value;
        }
      },
    });
    chart.area()
      .position('date*value')
      .color('city', (city) => {
        if (city == "上年同期") {
          return "#D1DDF6";
        } else if (city == "当期") {
          return "#5A8BEE";
        }
      });
    chart.line()
      .position('date*value')
      .color('city', (city) => {
        if (city == "上年同期") {
          return "#D1DDF6";
        } else if (city == "当期") {
          return "#5A8BEE";
        }
      }).size(1);
    chart.render();
    // 注意：需要把chart return 出来

    return chart;
  },
  kernelChart() {
    chartComponent = this.selectComponent('#publishCanvas');
    let that = this,
      _obj = this.data.kernelList,
      _arr1 = [],
      _arr2 = [],
      _arr3 = [];
    _obj.current_data.map((value, key) => {
      if (value.week_range) {
        _arr1.push(value.date + '（' + value.week_range + '）')
      } else {
        _arr1.unshift(value.date)
      }
      _arr2.unshift(value.value)
    })
    _obj.last_data.map((value, key) => {
      _arr3.unshift(value.value)
    })
    chartComponent.init((canvas, width, height, dpr) => {
      myChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myChart);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              show: false
            }
          },
          position: function (pos, params, dom, rect, size) {
            // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
            var obj = {
              top: '10%'
            };
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 10;
            return obj;
          },
          formatter(params) {
            console.log(params);
            let str = params[0].name + "\n";
            params.forEach((item) => {
              if (item.seriesName == '当期' && params.length > 1) {
                str += item.seriesName + '：' + item.value + '\n';
              } else {
                str += item.seriesName + '：' + item.value;
              }
            })
            return str;
          }
        },
        color: ['#5A8BEE', '#D1DDF6'],
        legend: {
          show: false,
          data: ['当期', '上年同期']
        },
        grid: {
          show: false,
          left: 5,
          right: 5,
          bottom: '5',
          top: 0,
          containLabel: false
        },
        xAxis: [{
          show: false,
          type: 'category',
          // boundaryGap: false,
          data: _arr1
        }],
        yAxis: [{
          show: false,
          type: 'value'
        }],
        series: [{
            name: '当期',
            type: 'line',
            areaStyle: {},
            lineStyle: {
              width: 1
            },
            areaStyle: {

            },
            // smooth: true,
            symbol: 'none',
            data: _arr2
          },
          {
            name: '上年同期',
            type: 'line',
            areaStyle: {},
            lineStyle: {
              width: 1
            },
            symbol: 'none',
            // smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: _arr3
          },
        ]
      };
      myOptions = option;
      myChart.setOption(option);
      return myChart
    });
  },
  // 地图加载
  setMapOption() {
    let that = this;
    const option = {
      tooltip: {
        trigger: 'item',
        backgroundColor: "#FFF",
        padding: [5, 10],
        textStyle: {
          color: '#FFF',
          fontSize: 12,
        },
        backgroundColor: "rgba(0,0,0,0.6)",
        borderColor: "#07193F",
        borderWidth: 1,
        formatter: `销售指数\n{b} : {c}`
      },
      geo: [{
        // 地理坐标系组件
        map: "china",
        roam: false, // 可以缩放和平移
        aspectScale: 0.8, // 比例
        layoutCenter: ["50%", "45%"], // position位置
        layoutSize: 360, // 地图大小，保证了不超过 360x360 的区域
        label: {
          // 图形上的文本标签
          normal: {
            show: true,
            textStyle: {
              color: "rgba(0, 0, 0, 0.9)",
              fontSize: '8'
            }
          },
          emphasis: { // 高亮时样式
            color: "#333"
          }
        },
        regions: that.data.setRegionList,
        itemStyle: {
          // 图形上的地图区域
          normal: {
            borderColor: "#FFF",
            areaColor: "#D1DDF5"
          },
          emphasis: {
            // 高亮时
            areaColor: "#4777D8",
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowBlur: 10,
            borderWidth: 0,
            shadowColor: "rgba(0, 0, 0, 0.2)"
          }
        }
      }],
      series: [{
        type: 'map',
        mapType: 'china',
        geoIndex: 0,
        roam: false, // 鼠标是否可以缩放
        label: {
          normal: {
            show: true
          },
          emphasis: {
            show: true
          }
        },
        data: [{
            name: '北京',
            value: that.randomData('北京')
          },
          {
            name: '天津',
            value: that.randomData('天津')
          },
          {
            name: '上海',
            value: that.randomData('上海')
          },
          {
            name: '重庆',
            value: that.randomData('重庆')
          },
          {
            name: '河北',
            value: that.randomData('河北')
          },
          {
            name: '河南',
            value: that.randomData('河南')
          },
          {
            name: '云南',
            value: that.randomData('云南')
          },
          {
            name: '辽宁',
            value: that.randomData('辽宁')
          },
          {
            name: '黑龙江',
            value: that.randomData('黑龙江')
          },
          {
            name: '湖南',
            value: that.randomData('湖南')
          },
          {
            name: '安徽',
            value: that.randomData('安徽')
          },
          {
            name: '山东',
            value: that.randomData('山东')
          },
          {
            name: '新疆',
            value: that.randomData('新疆')
          },
          {
            name: '江苏',
            value: that.randomData('江苏')
          },
          {
            name: '浙江',
            value: that.randomData('浙江')
          },
          {
            name: '江西',
            value: that.randomData('江西')
          },
          {
            name: '湖北',
            value: that.randomData('湖北')
          },
          {
            name: '广西',
            value: that.randomData('广西')
          },
          {
            name: '甘肃',
            value: that.randomData('甘肃')
          },
          {
            name: '山西',
            value: that.randomData('山西')
          },
          {
            name: '内蒙古',
            value: that.randomData('内蒙古')
          },
          {
            name: '陕西',
            value: that.randomData('陕西')
          },
          {
            name: '吉林',
            value: that.randomData('吉林')
          },
          {
            name: '福建',
            value: that.randomData('福建')
          },
          {
            name: '贵州',
            value: that.randomData('贵州')
          },
          {
            name: '广东',
            value: that.randomData('广东')
          },
          {
            name: '青海',
            value: that.randomData('青海')
          },
          {
            name: '西藏',
            value: that.randomData('西藏')
          },
          {
            name: '四川',
            value: that.randomData('四川')
          },
          {
            name: '宁夏',
            value: that.randomData('宁夏')
          },
          {
            name: '海南',
            value: that.randomData('海南')
          },
          {
            name: '台湾',
            value: that.randomData('台湾')
          },
          {
            name: '香港',
            value: that.randomData('香港')
          },
          {
            name: '澳门',
            value: that.randomData('澳门')
          }
        ]
      }],
      toolbox: {
        show: false,
      },
    };
    mapOptions = option;

    myMap.setOption(option);
  },
  initChartMap() {
    let that = this;
    oneComponent.init((canvas, width, height, dpr) => {
      myMap = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      canvas.setChart(myMap);
      echarts.registerMap('china', geoJson); // 绘制中国地图
      that.setMapOption();
      return myMap
    });
  },
  randomData(_name) {
    // console.log(888, this.data.regionList)
    let _value = 0;
    for (let i = 0; i < this.data.regionList.length; i++) {
      if (this.data.regionList[i].name == _name) {
        _value = this.data.regionList[i].sale_total;
      }
    }
    return _value;
  },
  // 跳转商品详情
  onClick(e) {
    // console.log(e);
    common.toDetail(e.currentTarget.dataset.id)
  },
  // 时间切换
  change(e) {
    this.setData({
      period: e.detail.period,
      date_type: e.detail.date_type,
      start_date: e.detail.start_date
    })
    wx.showLoading({
      mask: true
    })
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    this.getBaseInfo();
    this.getChartData();
    this.getGoodsData();
    this.getCateData();
    this.getRegionData();
  },
  mapChange(e) {
    // console.log(456, e)
    this.setData({
      visible: e.detail.visible
    })
    if (e.detail.visible) {
      oneComponent = this.selectComponent('#chartmap');
      wx.nextTick(() => {
        this.initChartMap();
      })
    }
  },
  changeChoose(e) {
    this.setData({
      choose: e.currentTarget.dataset.id,
      type: e.currentTarget.dataset.type
    });
    wx.showLoading({
      mask: true
    })
    this.getChartData();
  },
  openRank(event) {
    // console.log(event.currentTarget.dataset.id)
    this.getCateGoodsData(event.currentTarget.dataset.id);
  },
  onClose() {
    this.setData({
      visible: true,
      show: false
    });
    oneComponent = this.selectComponent('#chartmap');
    wx.nextTick(() => {
      this.initChartMap();
    })
  },
  renderCanvas() {
    this.setData({
      shareShow: false,
      visible: false,
    })
    // Toast('该页面暂未开放画报功能！');
    // return;
    wx.showLoading({
      mask: false,
      title: "数据画报生成中"
    })
    let that = this;
    let componentId = "#publishCanvas";
    let width, height, destWidth, destHeight;
    // 获取canvas高度
    if (this.data.chartList.length > 0) {
      console.log(147)
      const query = wx.createSelectorQuery()
      query.select(componentId).boundingClientRect()
      query.exec(function (rects) {
        rects.forEach(function (rect, n) {
          width = rect.width;
          height = rect.height;
          destWidth = rect.width;
          destHeight = rect.height;
          // console.log(111, destHeight)
        })
        myChart.on("finished", () => {
          console.log("开始转换")
          console.log(555, that.selectComponent(componentId).canvasToTempFilePath)

          that.selectComponent(componentId).canvasToTempFilePath({
            x: 0,
            y: 0,
            width,
            height,
            // 截取canvas的宽度
            destWidth,
            // 截取canvas的高度    
            destHeight,
            success: res => {
              console.log("转换图片成功", res.tempFilePath)
              that.setData({
                chartSrc: res.tempFilePath,
              })
            },
            fail: res => {
              console.log("转换图片失败", res)
            },
            complete: res => {
              console.log("转换动作结束", res)
              // canvas 画图
              that.canvasHtml();
            }
          });
        });
        myChart.setOption(myOptions);
      })
    } else {
      // canvas 画图
      that.canvasHtml();
    }
  },
  canvasHtml() {
    this.widget = this.selectComponent('.widget');
    let wxml = '',
      that = this,
      _title = JSON.parse(wx.getStorageSync('currentOrganize')),
      _info = JSON.parse(wx.getStorageSync('initInfo'));
    wxml += `
      <view class="canvas-content">
        <view class="liubai"></view>`;
    wxml += `<view class="head">
              <text class="sjjb">本社数据</text>`
    if (_title.organization_name.length < 20) {
      wxml += `<text class="orgtitle">` + _title.organization_name + `</text>`;
    } else {
      wxml += `<text class="orgtitle">` + _title.organization_name.slice(0, 17) + '...' + `</text>`
    }
    wxml += `</view>`;
    // wxml += `<view class="account">
    //           <text class="you">由</text>
    //           <text class="mingzi">` + _info.account + `分享</text>
    //         </view>`;
    wxml += `<view class="choosetime">
            <image class="img" src="https://bodao.mhuoba.com/static/wximages/rili.png"></image>
            <text class="time">` + this.data.time + `</text>
          </view>`
    wxml += `<text class="zrxs">本社核心数据</text>`;
    if (this.data.chartPower) {
      wxml += `<view class="actual-block">
              <view class="block active">
                <text class="number">` + this.data.baseInfo.sale_total_info.now + `</text>
                <text class="text">本社销售指数</text>
              </view>
              <view class="block">
                <text class="number">` + this.data.baseInfo.sale_ratio_info.now + `</text>
                <text class="text">行业占有率</text>
              </view>
            </view>`
      wxml += `<view class="actual-block">
            <view class="block">
              <text class="number">` + this.data.baseInfo.sale_rank_info.now + `</text>
              <text class="text">行业排名</text>
            </view>
            <view class="block">
              <text class="number">` + this.data.baseInfo.onsale_goods_info.now + `</text>
              <text class="text">动销品种</text>
            </view>
          </view>`
      if (this.data.chartList.length > 0) {
        wxml += `<image class="chartimage" src="` + this.data.chartSrc + `"></image>`
      } else {
        wxml += `<text class="nodata">暂无图表数据</text>`
      }
    } else {
      wxml += `<text class="nodata nodata1">暂无图表数据</text>`
    }
    wxml += `<view class="greyblock"></view>`;
    wxml += `<text class="zrxs">品种销售排行</text>`;
    wxml += `<view class="three zs">
              <text class="tushu">图书信息</text>
              <text class="tushu">销售指数</text>
            </view>`
    if (this.data.goodsPower) {
      if (this.data.goodsList.length > 0) {
        let goodsArr = this.data.goodsList.slice(0, 5);
        for (let i = 0; i < goodsArr.length; i++) {
          wxml += `<view class="three xiao">
                                    <text class="paiming">` + goodsArr[i].sale_rank + `</text>`;
          if (goodsArr[i].cover_pic) {
            let _src = goodsArr[i].cover_pic;
            if (_src.indexOf('https:') > -1) {
              _src = goodsArr[i].cover_pic;
            } else {
              _src = goodsArr[i].cover_pic.replace(/http/, 'https');
            }
            wxml += `<image class="cover" src="` + _src + `"></image>`
          } else {
            wxml += `<view class="no-image"></view>`
          }
          if (goodsArr[i].goods_name.length > 18) {
            wxml += `<text class="goodsname">` + goodsArr[i].goods_name.slice(0, 18) + '...' + `</text>`
          } else {
            wxml += `<text class="goodsname">` + goodsArr[i].goods_name + `</text>`
          }
          wxml += `<text class="saletotal">` + goodsArr[i].sale_total + `</text>
                                  </view>`
        }
      } else {
        wxml += `<text class="nodata nodata2">暂无数据</text>`
      }
    } else {
      wxml += `<text class="nodata nodata2">暂无权限</text>`
    }
    wxml += `<view class="greyblock"></view>`;
    wxml += `<text class="zrxs">类目销售分析</text>`;
    if (this.data.catePower) {
      if (this.data.cateList.length > 0) {
        let cateArr = this.data.cateList.slice(0, 3);
        for (let j = 0; j < cateArr.length; j++) {
          wxml += `<view class="cate-list">
                  <text class="cate-name">` + cateArr[j].category_name + `</text>
                  <view class="cate-xs">
                    <text class="cate-sale">` + cateArr[j].sale_total + `</text>
                    <text class="cate-zs">销售指数</text>
                  </view>
                  <view class="cate-bs">
                    <text class="cate-rank">` + cateArr[j].supplier_rank + `</text>
                    <text class="cate-pm">本社排名</text>
                  </view>
                  <view class="cate-bs">
                    <text class="cate-rank">` + cateArr[j].memo.goods_nums + `</text>
                    <text class="cate-pm">前百品种</text>
                  </view>
                  <image class="cate-img" src="https://bodao.mhuoba.com/static/wximages/arrow.png"></image>
                </view>`
        }
      } else {
        wxml += `<text class="nodata">暂无数据</text>`
      }
    } else {
      wxml += `<text class="nodata">暂无权限</text>`
    }
    wxml += `<view class="greyblock mt"></view>`;
    wxml += `<text class="zrxs">地域销售分析</text>`;
    wxml += `<view class="region-list">
              <text class="region-pm">排名</text>
              <text class="region-sf">省份</text>
              <text class="region-dz">读者基数</text>
              <text class="region-xs">销售指数</text>
            </view>`;
    if (this.data.regionPower) {
      if (this.data.regionList.length > 0) {
        let regionArr = this.data.regionList.slice(0, 3);
        for (let l = 0; l < regionArr.length; l++) {
          wxml += `<view class="region-list">
                <text class="region-pm cl">` + regionArr[l].rank + `</text>
                <text class="region-sf cl">` + regionArr[l].name + `</text>
                <text class="region-dz lg">` + regionArr[l].reader_total + `</text>
                <text class="region-xs lg">` + regionArr[l].sale_total + `</text>
              </view>`;
        }
      } else {
        wxml += `<text class="nodata nodata3">暂无数据</text>`
      }
    } else {
      wxml += `<text class="nodata nodata3">暂无权限</text>`
    }
    wxml += `<view class="greyblock mt"></view>`;
    wxml += `<text class="zrxs">本社概况</text>`;
    if (this.data.indexPower) {
      wxml += `<view class="publish">
                <view class="zspz">
                <text class="publish-text">在售品种数</text>
                  <text class="publish-num">` + this.data.baseInfo.on_sale_num + `</text>
                </view>
                <view class="zspz">
                  <text class="publish-text">读者基数</text>
                  <text class="publish-num">` + this.data.baseInfo.reader_num + `</text>
                </view>
                <view class="zspz">
                  <text class="publish-text">累计销售指数</text>
                  <text class="publish-num">` + this.data.baseInfo.sale_total + `</text>
                </view>
              </view>`;
    } else {
      wxml += `<text class="nodata nodata4">暂无权限</text>`
    }
    wxml += `<view class="zhichi">
              <image class="ercode" src="https://bodao.mhuoba.com/static/wximages/ercode.png"></image>
              <text class="jishu">博道出版数据实验室提供技术支持</text>
            </view>`;
    wxml += `</view>`;
    let style = {
      canvasContent: {
        backgroundColor: '#FFF',
        width: 375,
        height: 1290,
        padding: 10,
      },
      liubai: {
        width: 355,
        height: 30
      },
      head: {
        width: 355,
        height: 23,
        flexDirection: 'row',
        alignItems: 'center'
      },
      sjjb: {
        width: 68,
        height: 23,
        fontSize: 16,
        color: '#07193F',
      },
      orgtitle: {
        width: 280,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginLeft: 5
      },
      account: {
        width: 355,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        flexDirection: 'row',
        marginTop: 10
      },
      you: {
        width: 12,
        height: 18,
      },
      mingzi: {
        width: 335,
        height: 18,
      },
      choosetime: {
        width: 355,
        height: 18,
        marginTop: 15,
        flexDirection: 'row',
        alignItems: 'center',
      },
      img: {
        width: 16,
        height: 16,
      },
      time: {
        width: 335,
        height: 18,
        fontSize: 12,
        color: '#07193F',
        marginLeft: 5,
        marginTop: 2
      },
      zrxs: {
        width: 355,
        height: 20,
        fontSize: 14,
        color: '#07193F',
        marginTop: 15
      },
      actualBlock: {
        width: 355,
        height: 60,
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginTop: 10
      },
      block: {
        width: 170,
        height: 60,
        backgroundColor: '#F4F7FD',
        borderRadius: 4
      },
      number: {
        width: 170,
        height: 23,
        fontSize: 16,
        color: '#07193F',
        textAlign: 'center',
        marginTop: 10,
      },
      text: {
        width: 170,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        // marginTop:5,
        textAlign: 'center'
      },
      chartimage: {
        width: 355,
        height: 110,
        marginTop: 5,
        marginBottom: 5
      },
      greyblock: {
        width: 375,
        height: 4,
        backgroundColor: '#F4F7FD',
        marginLeft: -10
      },
      nodata: {
        width: 355,
        height: 110,
        lineHeight: 110,
        color: '#7789AF',
        fontSize: 12,
        textAlign: 'center',
      },
      nodata1: {
        height: 250,
        lineHeight: 250,
      },
      nodata2: {
        height: 200,
        lineHeight: 200,
      },
      nodata3: {
        height: 85,
        lineHeight: 85,
      },
      nodata4: {
        height: 50,
        lineHeight: 50,
      },
      three: {
        width: 355,
        height: 26,
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 2
      },
      zs: {
        justifyContent: 'space-between'
      },
      tushu: {
        width: 48,
        height: 18,
        fontSize: 12,
        color: '#7789AF'
      },
      xiao: {
        height: 39,
        marginBottom: 10
      },
      paiming: {
        width: 22,
        height: 18,
        fontSize: 12,
        color: '#07193F'
      },
      cover: {
        width: 36,
        height: 36,
      },
      noImage: {
        width: 36,
        height: 36,
        backgroundColor: '#D1DDF6'
      },
      goodsname: {
        width: 220,
        height: 20,
        fontSize: 12,
        color: '#07193F',
        flexWrap: 'wrap',
        marginLeft: 5
      },
      saletotal: {
        width: 67,
        height: 20,
        fontSize: 14,
        color: '#7789AF',
        textAlign: 'right'
      },
      cateList: {
        width: 355,
        height: 55,
        backgroundColor: '#F4F7FD',
        borderRadius: 10,
        flexDirection: 'row',
        alignItems: 'center',
        padding: 10,
        marginTop: 10,
      },
      cateName: {
        width: 95,
        height: 35,
        verticalAlign: 'middle',
        fontSize: 14,
        color: '#07193F',
        marginLeft: 10
      },
      cateXs: {
        width: 70,
        height: 40,
        flexDirection: 'column',
        justifyContent: 'space-between',
        marginLeft: 10
      },
      cateSale: {
        width: 70,
        height: 20,
        fontSize: 14,
        color: '#07193F',
        textAlign: 'center'
      },
      cateZs: {
        width: 70,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        textAlign: 'center'
      },
      cateBs: {
        width: 50,
        height: 40,
        flexDirection: 'column',
        justifyContent: 'space-between',
        marginLeft: 10
      },
      cateRank: {
        width: 50,
        height: 20,
        fontSize: 14,
        color: '#7789AF',
        textAlign: 'center'
      },
      catePm: {
        width: 50,
        height: 18,
        fontSize: 12,
        color: '#7789AF',
        textAlign: 'center'
      },
      cateImg: {
        width: 20,
        height: 15,
        marginLeft: 10
      },
      regionList: {
        width: 355,
        height: 20,
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 10,
      },
      regionPm: {
        width: 55,
        height: 20,
        fontSize: 12,
        color: '#7789AF'
      },
      regionSf: {
        width: 50,
        height: 20,
        fontSize: 12,
        color: '#7789AF'
      },
      regionDz: {
        width: 150,
        height: 20,
        fontSize: 12,
        color: '#7789AF',
        textAlign: 'right'
      },
      regionXs: {
        width: 100,
        height: 20,
        fontSize: 12,
        color: '#7789AF',
        textAlign: 'right',
      },
      zhichi: {
        width: 355,
        height: 78,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: "center",
      },
      ercode: {
        width: 48,
        height: 48,
      },
      jishu: {
        width: 180,
        height: 18,
        color: '#07193F',
        fontSize: 12,
        marginLeft: 15
      },
      publish: {
        width: 355,
        height: 40,
        flexDirection: 'row',
        marginTop: 10
      },
      zspz: {
        width: 118,
        height: 40,
        flexDirection: 'column',
        justifyContent: 'space-between',
      },
      publishNum: {
        width: 118,
        height: 20,
        fontSize: 14,
        color: '#07193F'
      },
      publishText: {
        width: 118,
        height: 18,
        fontSize: 12,
        color: '#7789AF'
      },
      cl: {
        color: '#07193F',
      },
      lg: {
        fontSize: 14,
        color: '#7789AF',
      },
      mt: {
        marginTop: 10
      }
    }
    console.log(22, {
      wxml,
      style
    });
    console.log('widget', this.widget, this.widget1)
    const p1 = this.widget.renderToCanvas({
      wxml,
      style
    })
    p1.then((res) => {
      // console.log('canvasContent', res)
      this.canvasContent = res
      wx.hideLoading();
      Dialog.confirm({
          title: '',
          message: '画报生成成功，是否保存至手机相册',
        })
        .then(() => {
          // on confirm
          that.extraImage();
        })
        .catch(() => {
          // on cancel
        });
    })
  },
  extraImage() {
    let that = this;
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      console.log('最后1', res.tempFilePath)
      that.setData({
        src: res.tempFilePath,
        // width: this.canvasContent.layoutBox.width,
        // height: this.canvasContent.layoutBox.height
      })
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res) {
          console.log('保存图片成功', res)
          Toast('成功保存至手机相册！')
        },
        fail(res) {
          console.log('保存图片失败', res)
          Toast('保存至手机相册失败！')
        },
        complete(res) {
          that.setData({
            visible: true
          });
          oneComponent = that.selectComponent('#chartmap');
          wx.nextTick(() => {
            that.initChartMap();
          })
          console.log('保存图片动作结束', res)
          wx.hideLoading();
        }
      })
    })
  },
  tabChange(event) {
    let _index = event.detail.index,
      that = this;
    // console.log(_index)
    this.setData({
      isHand: false,
    })
    if (_index == 0) {
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
    } else if (_index == 1) {
      wx.pageScrollTo({
        selector: ".goods-card",
        duration: 300
      })
    } else if (_index == 2) {
      wx.pageScrollTo({
        selector: ".cate-card",
        duration: 300
      })
    } else if (_index == 3) {
      wx.pageScrollTo({
        selector: ".region-card",
        duration: 300
      })
    }
    setTimeout(function () {
      that.setData({
        isHand: true,
      })
    }, 1000)
  },
  touchMove() {
    // console.log(1);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchCancel() {
    // console.log(2);
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  touchEnd() {
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('0').step();
    this.setData({
      animationData: animation.export()
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.widget = this.selectComponent('.widget')

    if (wx.getStorageSync("token")) {
      let _title = JSON.parse(wx.getStorageSync('currentOrganize')),
        that = this;
      oneComponent = this.selectComponent('#chartmap');
      wx.setNavigationBarTitle({
        title: _title.organization_name,
      })
      this.setData({
        active: 0,
        isHand: false,
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
      wx.showLoading({
        mask: true
      })
      setTimeout(function () {
        that.setData({
          isHand: true,
        })
      }, 1000)
      this.getBaseInfo();
      this.getChartData();
      this.getGoodsData();
      this.getCateData();
      this.getRegionData();
    } else {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.hideLoading();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  onPageScroll: function (e) {
    // console.log(e)
    let that = this;
    var animation = wx.createAnimation({
      duration: 500
    })
    animation.translateX('80rpx').step();
    this.setData({
      animationData: animation.export()
    });
    if (this.data.isHand) {
      let coreHeight = this.data.coreHeight,
        goodsHeight = this.data.goodsHeight,
        cateHeight = this.data.cateHeight,
        regionHeight = this.data.regionHeight;
      // console.log(coreHeight, goodsHeight, cateHeight, regionHeight);
      if (e.scrollTop < coreHeight) {
        this.setData({
          active: 0
        })
      } else if (e.scrollTop < (coreHeight + goodsHeight + 20) && e.scrollTop > coreHeight) {
        this.setData({
          active: 1
        })
      } else if (e.scrollTop < (coreHeight + goodsHeight + 40 + cateHeight) && e.scrollTop > (coreHeight + goodsHeight + 20)) {
        this.setData({
          active: 2
        })
      } else if ((coreHeight + goodsHeight + 40 + cateHeight) < e.scrollTop) {
        this.setData({
          active: 3
        })
      }
      setTimeout(() => {
        var animation = wx.createAnimation({
          duration: 500
        })
        animation.translateX('0').step();
        this.setData({
          animationData: animation.export()
        });
      }, 1500)
      // console.log(this.data.active)
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "博道出版数据实验室"
    }
  }
})